package com.copa.gameStore.holder;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.copa.gameStore.client.UserClient;
import com.copa.gameStore.domain.User;
import com.copa.gameStore.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.util.Objects;

/**
 * @author copa
 * @createDate 2022-10-24 15:34
 * @function 避免重复编写
 */
@Component
public class LoginUserHolder {

    @Resource
    private UserClient userClient;

    public UserVo getUser() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userJson = request.getHeader("user");
        if (Objects.nonNull(userJson)) {
            JSONObject userJsonObject = new JSONObject(userJson);
            User user = userClient.findByUsername(userJsonObject.getStr("username"));
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            userVo.setAuthorities(Convert.toList(String.class, userJsonObject.get("authorities")));
            return userVo;

        }
        throw new ValidationException("请登录~");
    }
}
